﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace ProjectStudy.PreventRepeatedLogin
{
    public partial class 防止重复登陆 : System.Web.UI.Page
    {
        //防止用户重复登陆
        //1.web.config添加<sessionState mode="InProc" cookieless="false" timeout="1"></sessionState>
        //2.global.asax中Session_End函数添加代码
        //3.在注销事件中添加Session_End函数中相同的代码

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = tbUserName.Text.ConvertObjToStr();
            string password = tbPwd.Text.ConvertObjToStr();
            if (username == "cxf" && password == "111")
            {
                Hashtable h = (Hashtable)Application["Online"];
                if (CheckUserIsLogin(username, h))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "1", "<script>alert('您已登录，请勿重复登陆')</script>");
                }
                else
                {
                    if (h == null)
                    {
                        h = new Hashtable();
                    }
                    h[Session.SessionID] = username;
                    Application["Online"] = h;
                    Session["username"] = username;
                    ClientScript.RegisterStartupScript(this.GetType(), "2", "<script>alert('登录成功')</script>");
                    div1.Visible = false;
                    Response.Write("登录成功");
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "3", "<script>alert('账号或密码错误')</script>");
            }
        }

        private bool CheckUserIsLogin(string username,Hashtable h)
        {
            if (username == "" || username == null || h == null)
            {
                return false;
            }
            else
            {
                IDictionaryEnumerator e1 = h.GetEnumerator();
                bool isExist = false;
                while (e1.MoveNext())
                {
                    if (e1.Value.ConvertObjToStr() == username)
                    {
                        isExist = true;
                        break;
                    }
                }
                return isExist;
            }
        }
    }
}